<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="广告状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择广告状态" clearable>
          <el-option
            v-for="dict in dict.type.ad_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['maincode:advertisements:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="paginatedData" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单id" align="center" prop="id" />
      <el-table-column label="订单状态" align="center" prop="orderStatus" >
        <template slot-scope="scope">
          <div v-if="scope.row.orderStatus == 0">待付款</div>
          <div v-if="scope.row.orderStatus == 1">待发货</div>
          <div v-if="scope.row.orderStatus == 2">待收货</div>
          <div v-if="scope.row.orderStatus == 3">完成</div>
        </template>
      </el-table-column>
      <el-table-column label="订单总金额" align="center" prop="totalPrice" width="180"></el-table-column>
      <el-table-column label="商品单价" align="center" prop="unitPrice" width="180"></el-table-column>
      <el-table-column label="购买数量" align="center" prop="quantity" />

      <el-table-column label="商品图片"  prop="imageUrl" >
        <template  slot-scope="scope" width="90">
          <!-- <img style="width:80px;height:80px;border:none;" :src="uploadImgUrl+scope.row.targetImg"> -->
          <ImagePreview style="width:80px;height:80px;border:none;" :src="scope.row.imgUrl" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['maincode:advertisements:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['maincode:advertisements:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="display: flex;flex-direction: row-reverse;margin-top: 10px;">
        <el-pagination background v-model:current-page="currpage" v-model:page-size="pagesize" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange"></el-pagination>
      </div>

    <!-- 添加或修改广告对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="商品名称" prop="title">
          <el-radio-group v-model="form.type" size="large">
              <el-radio-button label="乐器" value="0" />
              <el-radio-button label="活动周边" value="1" />
              <el-radio-button label="音乐学习" value="2" />
          </el-radio-group>
      </el-form-item>
        <el-form-item label="商品名称" prop="title">
          <el-input v-model="form.title" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="价格">
          <el-input-number  :min="1" v-model="form.clicks"/>
        </el-form-item>
        <el-form-item label="库存">
          <el-input-number  :min="0" v-model="form.kucun"/>
        </el-form-item>
        <el-form-item label="商品图片" prop="imageUrl">
          <image-upload :limit="1" v-model="form.imageUrl"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改广告对话框 -->
    <el-dialog :title="title" :visible.sync="updata" width="1000px" append-to-body>
      <el-form ref="updataForm" :model="updataForm" :rules="rules" label-width="80px">
      <el-form-item label="订单状态" prop="title">
          <el-radio-group v-model="updataForm.type" size="large">
              <el-radio-button label="待付款" value="待付款" />
              <el-radio-button label="待发货" value="待发货" />
              <el-radio-button label="待收货" value="待收货" />
              <el-radio-button label="完成订单" value="完成订单" />
          </el-radio-group>
      </el-form-item>
        <el-form-item label="总金额">
          <el-input-number  :min="1" v-model="updataForm.title"/>
        </el-form-item>
        <el-form-item label="购买数量">
          <el-input-number  :min="1" v-model="updataForm.clicks"/>
        </el-form-item>
        <el-form-item label="商品单价">
          <el-input-number  :min="0" v-model="updataForm.kucun"/>
        </el-form-item>
        <el-form-item label="商品图片" prop="imageUrl">
          <image-upload :limit="1" v-model="updataForm.imageUrl"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitupdataForm">确 定</el-button>
        <el-button @click="updata = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAllOrder,addProdcut,deleteOrder,updateOrder,getmainOrder } from '@/api/store/index'
export default {
  name: "Advertisements",
  dicts: ['ad_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
              // 分页
              pagesize:10,
        currpage:1,
      // 广告表格数据
      advertisementsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      updata:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        content: null,
        link: null,
        startTime: null,
        expirationTime: null,
        clicks: null,
        status: null,
        imageUrl: null,
      },
      Idproduct:0,
      // 表单参数
      form: {},
      updataForm:{
        type:''
      },
      NewData:{},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "广告标题不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "价格不能为空", trigger: "blur" }
        ],
        link: [
          { required: true, message: "库存需要填写", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "上线时间不能为空", trigger: "blur" }
        ],
        expirationTime: [
          { required: true, message: "过期时间不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "广告状态不能为空", trigger: "change" }
        ],
      },
      
    };
  },
  created() {
    this.getList();
  },
  computed:{
      paginatedData() {
        const start = (this.currpage - 1) * this.pagesize;
        const end = start + this.pagesize;
        console.log(this.advertisementsList);
        return this.advertisementsList.slice(start, end);
      }
    },
  methods: {
    /** 查询广告列表 */
    getList() {
      this.loading = true;
      getAllOrder().then(response => {
        this.advertisementsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        adId: null,
        title: null,
        content: null,
        link: null,
        startTime: null,
        expirationTime: null,
        clicks: null,
        status: null,
        imageUrl: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.adId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.updata = true
      this.Idproduct = row
      getmainOrder(row.id).then(res => {
        if(res.data.orderStatus == 0){
          this.updataForm.type = '待付款'
        }else if(res.data.orderStatus == 1){
          this.updataForm.type = '待发货'
        }else if(res.data.orderStatus == 2){
          this.updataForm.type = '待收货'
        }else if(res.data.orderStatus == 3){
          this.updataForm.type = '完成订单'
        }
          this.updataForm.clicks = res.data.quantity
          this.updataForm.imageUrl = res.data.imgUrl
          this.updataForm.kucun = res.data.unitPrice
          this.updataForm.title = res.data.totalPrice
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let localTypeI; // ✅ Create a new variable
          if(this.form.type == '乐器'){
              localTypeI = 0
          } else if(this.form.type == '活动周边'){
              localTypeI = 1
          }else{
              localTypeI = 2
          }
          addProdcut({
              price:this.form.clicks,
              imgUrl:this.form.imageUrl,
              stock:this.form.kucun,
              name:this.form.title,
              categoryName:localTypeI
          }).then(res => {
              this.$modal.msgSuccess("增加成功");
              this.open = false;
              this.getList();
          })
        }
      });
    },
    submitupdataForm(){
      this.$refs["updataForm"].validate(valid => {
        if (valid) {
          let localTypeI; // ✅ Create a new variable
          if(this.updataForm.type == '待付款'){
              localTypeI = 0
          } else if(this.updataForm.type == '待发货'){
              localTypeI = 1
          }else if(this.updataForm.type == '待收货'){
            localTypeI = 2
          }else if(this.updataForm.type == '完成订单'){
            localTypeI = 3
          }
          updateOrder({
              id:this.Idproduct.id,
              userId:this.Idproduct.userId,
              productId:this.Idproduct.productId,
              quantity:this.updataForm.clicks,
              imgUrl:this.updataForm.imageUrl,
              unitPrice:this.updataForm.kucun,
              totalPrice:this.updataForm.title,
              orderStatus:localTypeI
          }).then(res => {
              this.$modal.msgSuccess("修改成功");
              this.updata = false;
              this.updataForm = {}
              this.getList();
          })
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const adIds = row.id
      this.$modal.confirm('是否确认删除该订单').then(function() {
        return deleteOrder(adIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('maincode/advertisements/export', {
        ...this.queryParams
      }, `advertisements_${new Date().getTime()}.xlsx`)
    },
    // 分页
    handleSizeChange(size){
        this.pagesize = size;
        this.currpage = 1;  // 切换页面大小时重新从第一页开始
      },
      handleCurrentChange(page){
        this.currpage = page
      }
  }
};
</script>
